package com.ayf.payment.game.api.controller;

import cn.hutool.core.collection.CollUtil;
import com.ayf.payment.game.api.cache.redis.RedisCacheUtil;
import com.ayf.payment.game.api.dto.*;
import com.ayf.payment.game.api.dto.criteria.*;
import com.ayf.payment.game.api.dto.platform.NetConfigDTO;
import com.ayf.payment.game.api.dto.platform.PaymentProductDTO;
import com.ayf.payment.game.api.entity.Merchant;
import com.ayf.payment.game.api.entity.ProxyGroup;
import com.ayf.payment.game.api.entity.ProxyNetConfig;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.service.*;
import com.ayf.payment.game.api.service.platform.NetConfigService;
import com.ayf.payment.game.api.service.platform.PaymentProductService;
import com.ayf.payment.game.api.type.CommonConstants;
import com.ayf.payment.game.api.type.LoginType;
import com.ayf.payment.game.api.type.MerchantStatus;
import com.ayf.payment.game.api.type.SMSType;
import com.ayf.payment.game.api.utils.CommonResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swwx.charm.commons.lang.utils.BeanConvertUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 代理商控制层
 * @Author: zh-liang
 * @Date : 2020-03-10 11:12
 */
@RequestMapping("/v/proxy")
@RestController
public class ProxyRelController {

    @Autowired
    private ProxyNetConfigService proxyNetConfigService;

    @Autowired
    private ProxyGroupService proxyGroupService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private PartitionService partitionService;

    @Autowired
    private MerchantPermissionService merchantPermissionService;
    @Autowired
    private PaymentProductService paymentProductService;

    @Autowired
    private NetConfigService netConfigService;

    @Autowired
    private MerchantProxyRelService merchantProxyRelService;

    /**
     * 查询代理商网络配置
     *
     * @param merchantDTO
     * @return
     */
    @PostMapping("/selectNetConfig")
    public CommonResult<ProxyNetConfig> selectNetConfig(MerchantDTO merchantDTO) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        ProxyNetConfig proxyNetConfig = proxyNetConfigService.selectByMerchantId(merchantDTO.getId());
        return new CommonResult<ProxyNetConfig>(CommonConstants.RETURN_SUCCESS, "查询代理商网络配置成功", proxyNetConfig);
    }

    /**
     * 更新代理商网络配置
     *
     * @param proxyNetConfig
     * @param merchantDTO
     * @return
     */
    @PostMapping("/updateNetConfig")
    public CommonResult updateNetConfig(@RequestBody ProxyNetConfig proxyNetConfig, MerchantDTO merchantDTO) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        proxyNetConfig.setMerchantId(merchantDTO.getId());
        if (proxyNetConfigService.update(proxyNetConfig)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "更新代理商网络配置成功");

        }
        return new CommonResult(CommonConstants.RETURN_SUCCESS, "更新代理商网络配置失败");
    }

    /**
     * 添加用户分组
     *
     * @param proxyGroupCriteria
     * @param merchantDTO
     * @return
     */
    @PostMapping("/addGroup")
    public CommonResult addGroup(@RequestBody ProxyGroupCriteria proxyGroupCriteria, MerchantDTO merchantDTO) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        proxyGroupCriteria.setMerchantId(merchantDTO.getId());
        if (proxyGroupService.insert(proxyGroupCriteria)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "添加分组成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "添加分组失败");
    }

    /**
     * 查询代理商分组
     *
     * @param merchantDTO
     * @param ProxyGroupCriteria
     * @return
     */
    @PostMapping("/selectGroup")
    public CommonResult<PageDTO> selectGroup(MerchantDTO merchantDTO, @RequestBody ProxyGroupCriteria ProxyGroupCriteria) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        ProxyGroupCriteria.setMerchantId(merchantDTO.getId());
        PageHelper.startPage(ProxyGroupCriteria.getPageNum(), ProxyGroupCriteria.getPageSize());
        List<ProxyGroup> groups = proxyGroupService.selectGroup(merchantDTO.getId());
        PageInfo<ProxyGroup> pageInfo = new PageInfo<>(groups);
        PageDTO groupDTO = BeanConvertUtils.convert(pageInfo, PageDTO.class);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询代理商分组成功", groupDTO);
    }

    /**
     * 查询所有分组
     *
     * @param merchantDTO
     * @param ProxyGroupCriteria
     * @return
     */
    @PostMapping("/selectAllGroup")
    public CommonResult<List<ProxyGroup>> selectAllGroup(MerchantDTO merchantDTO,
                                                         @RequestBody ProxyGroupCriteria ProxyGroupCriteria) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        ProxyGroupCriteria.setMerchantId(merchantDTO.getId());
        List<ProxyGroup> groups = proxyGroupService.selectGroup(merchantDTO.getId());
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询代理商分组成功", groups);
    }

    /**
     * 查询分组详情
     *
     * @param merchantDTO
     * @param proxyGroupCriteria
     * @return
     */
    @PostMapping("/selectGroupInfo")
    public CommonResult<ProxyGroupCriteria> selectGroupInfo(MerchantDTO merchantDTO, @RequestBody ProxyGroupCriteria proxyGroupCriteria) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        proxyGroupCriteria.setMerchantId(merchantDTO.getId());
        ProxyGroupCriteria groupInfo = proxyGroupService.selectGroupInfo(proxyGroupCriteria);
        List<PaymentProductDTO> paymentProductDTOS = paymentProductService.selectAll();
        List<ProxyGroupRateDTO> groupRateList = new ArrayList<>();
        for (PaymentProductDTO dto : paymentProductDTOS) {
            ProxyGroupRateDTO rd = new ProxyGroupRateDTO();
            rd.setPayProductId(dto.getId());
            rd.setPayProductName(dto.getAliasName());
            rd.setPaymentRate(BigDecimal.ZERO);
            for (ProxyGroupRateDTO groupRate : groupInfo.getGroupRateList()) {
                if (dto.getId().equals(groupRate.getPayProductId())) {
                    rd.setPaymentRate(groupRate.getPaymentRate());
                    break;
                }
            }
            groupRateList.add(rd);
        }
        groupInfo.setGroupRateList(groupRateList);
        return new CommonResult<ProxyGroupCriteria>(CommonConstants.RETURN_SUCCESS, "查询分组详情成功", groupInfo);
    }

    /**
     * 更新用户分组
     *
     * @param proxyGroupCriteria
     * @return
     */
    @PostMapping("/updateGroup")
    public CommonResult updateGroup(MerchantDTO merchantDTO, @RequestBody ProxyGroupCriteria proxyGroupCriteria) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        proxyGroupCriteria.setMerchantId(merchantDTO.getId());
        if (proxyGroupService.updateGroup(proxyGroupCriteria)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "用户分组更新成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "用户分组更新失败");
    }

    /**
     * 删除用户分组
     *
     * @param proxyGroupCriteria
     * @return
     */
    @PostMapping("/deleteGroup")
    public CommonResult deleteGroup(@RequestBody ProxyGroupCriteria proxyGroupCriteria, MerchantDTO merchantDTO) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        proxyGroupCriteria.setMerchantId(merchantDTO.getId());
        if (proxyGroupService.deleteGroup(proxyGroupCriteria)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "删除用户分组成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "删除用户分组失败");
    }

    /**
     * 更改默认分组
     *
     * @param merchantDTO
     * @param proxyGroupCriteria
     * @return
     */
    @PostMapping("/defaults")
    public CommonResult defaults(MerchantDTO merchantDTO, @RequestBody ProxyGroupCriteria proxyGroupCriteria) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        proxyGroupCriteria.setMerchantId(merchantDTO.getId());
        if (proxyGroupService.updateGroupDefaults(proxyGroupCriteria)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "默认分组更改成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "默认分组更改失败");
    }

    /**
     * 添加下级商户
     *
     * @param lowerMerchantCriteria
     * @param merchantDTO
     * @return
     */
    @PostMapping("/addLower")
    public CommonResult addLower(@CookieValue("codeKey") String codeKey,
                                 @RequestBody LowerMerchantCriteria lowerMerchantCriteria, MerchantDTO merchantDTO) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        lowerMerchantCriteria.setMerchantId(merchantDTO.getId());
        if (StringUtils.isBlank(lowerMerchantCriteria.getCode())) {
            throw new ParameterException("图片验证码不能为空");
        }
        String code = redisCacheUtil.getObjectFromCache(codeKey);
        //验证验证码
        if (!lowerMerchantCriteria.getCode().equalsIgnoreCase(code)) {
            return new CommonResult(CommonConstants.RETURN_ERROR, "图片验证码输入错误");
        }
        if (merchantService.insertLowerMerchant(lowerMerchantCriteria)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "添加下级商户成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "添加下级商户失败");
    }

    /**
     * 下级商户自由注册（短信验证）
     *
     * @param lowerMerchantCriteria
     * @return
     */
    @PostMapping("/register")
    public CommonResult register(@RequestBody LowerMerchantCriteria lowerMerchantCriteria) {
        Merchant merchant =  merchantService.find(lowerMerchantCriteria.getMerchantId());
        if (merchant==null){
            throw new ParameterException("代理商户不存在");
        }
        if (!"PROXY".equals(merchant.getMerchantType())){
            throw new ParameterException("非代理商户，无权注册");
        }
        if (StringUtils.isBlank(lowerMerchantCriteria.getPhone())) {
            throw new ParameterException("手机号不能为空");
        }
//        if (StringUtils.isBlank(lowerMerchantCriteria.getCode())) {
//            throw new ParameterException("短信验证码不能为空");
//        }
//        String code = redisCacheUtil.getObjectFromCache(SMSType.REGISTER.name()+lowerMerchantCriteria.getPhone());
//        if (!lowerMerchantCriteria.getCode().equalsIgnoreCase(code)) {
//            return new CommonResult<>(CommonConstants.RETURN_ERROR, "代理下属商户注册失败，短信验证码输入错误", false);
//        }
        if (merchantService.insertLowerMerchant(lowerMerchantCriteria)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "代理下属商户注册成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "代理下属商户注册失败");
    }

    /**
     * 查询下级商户
     *
     * @param lower
     * @param merchantDTO
     * @return
     */
    @PostMapping("/selectLower")
    public CommonResult<PageDTO> selectLower(@RequestBody LowerMerchantCriteria lower,
                                             MerchantDTO merchantDTO) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        lower.setMerchantId(merchantDTO.getId());
        PageHelper.startPage(lower.getPageNum(), lower.getPageSize());
        List<LowerMerchantDTO> dtoList = merchantService.selectAllLower(lower);
        PageInfo<LowerMerchantDTO> pageInfo = new PageInfo<>(dtoList);
        PageDTO dto = BeanConvertUtils.convert(pageInfo, PageDTO.class);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询下级商户成功", dto);
    }

    /**
     * 查询下级商户信息
     *
     * @param lower
     * @return
     */
    @PostMapping("/selectLowerInfo")
    public CommonResult<LowerMerchantCriteria> selectLowerInfo(@RequestBody LowerMerchantCriteria lower,MerchantDTO merchantDTO) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        LowerMerchantCriteria info = merchantService.selectMerchantInfo(lower.getMerchantId());
        return new CommonResult<LowerMerchantCriteria>(CommonConstants.RETURN_SUCCESS, "查询商户信息成功", info);
    }

    /**
     * 更新下级商户信息
     *
     * @return
     */
    @PostMapping("/updateLowerInfo")
    public CommonResult updateLowerInfo(@RequestBody LowerMerchantCriteria lower,MerchantDTO merchantDTO) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        if (merchantService.updateMerchantInfo(lower)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "更新商户信息成功");

        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "更新商户信息失败");
    }

    /**
     * 更新下级商户分组
     *
     * @return
     */
    @PostMapping("/updateLowerGroup")
    public CommonResult updateLowerGroup(@RequestBody LowerMerchantCriteria lower,MerchantDTO merchantDTO) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        if (merchantService.updateMerchantGroup(lower)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "结算比例分组更新成功");
        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "结算比例分组更新失败");
    }

    /**
     * 代理商更新下级商户状态
     *
     * @param merchantCriteria
     * @return
     */
    @PostMapping("/proxyUpdateStatus")
    public CommonResult updateStatus(@RequestBody MerchantCriteria merchantCriteria,MerchantDTO merchantDTO) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        Merchant merchant = new Merchant();
        merchant.setId(merchantCriteria.getId());
        merchant.setStatus(merchantCriteria.getStatus());
        if (merchantService.update(merchant)) {
            return new CommonResult(CommonConstants.RETURN_SUCCESS, "更新商户状态成功");

        }
        return new CommonResult(CommonConstants.RETURN_ERROR, "更新商户状态失败");
    }

    /**
     * 代理商户直接登录下级商户
     *
     * @param merchantCriteria
     * @return
     */
    @PostMapping("/proxyLoginMerchant")
    public CommonResult<Map<String, Object>> adminLoginMerchant(@RequestBody MerchantCriteria merchantCriteria,MerchantDTO merchantDTO) {
        LogPortal.info("代理商户登录下属商户ID 代理商户ID:{} 下属商户ID:{} 操作IP:{}",merchantDTO.getId(),merchantCriteria.getId(),merchantDTO.getOperIp());
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        if (!merchantProxyRelService.checkProxyLowerMerchantId(merchantDTO.getId(),merchantCriteria.getId())){
            return new CommonResult(8100, "非代理下属商户，无权访问");
        }
        Token token = tokenService.createToken(merchantCriteria.getId(), merchantCriteria.getId(), LoginType.FATHER.name(),merchantDTO.getOperIp());
        Merchant merchant = merchantService.find(merchantCriteria.getId());
        if (merchant == null) {
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "进入商户后台失败，不存在此商户");
        }
        if (MerchantStatus.AUDITED.equals(merchant.getStatus())){
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "请联系运营人员审核，无法进入");
        } else if (MerchantStatus.DELETE.equals(merchant.getStatus())){
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "当前商户已删除，无法进入");
        }else if (MerchantStatus.PROHIBIT.equals(merchant.getStatus())){
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "当前商户已禁用，无法进入");
        }
        Map<String, Object> result = new HashMap<>(16);
        result.put("accessToken", token.getAccessToken());
        result.put("merchantStatus", merchant.getStatus().name());
        result.put("merchantType", merchant.getMerchantType());
        result.put("loginType", "proxy");
        MerchantPermissionDTO dto = merchantPermissionService.adminList(merchant.getMerchantType());
        result.put("permission", dto);
        result.put("type", "FATHER");
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "登录成功", result);
    }

    /**
     * 查询下属商户订单信息
     *
     * @param merchantDTO
     * @param orderCriteria
     * @return
     */
    @PostMapping("/orderList")
    public CommonResult<ChargeOrderResponseDTO> orderList(MerchantDTO merchantDTO,
                                                          @RequestBody OrderInfoCriteria orderCriteria) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        orderCriteria.setProxyId(merchantDTO.getId());
        ChargeOrderResponseDTO dto = orderService.selectOrderList(orderCriteria);
        return new CommonResult<ChargeOrderResponseDTO>(CommonConstants.RETURN_SUCCESS, "查询成功", dto);
    }

    /**
     * 查询下级商户分区
     *
     * @param merchantDTO
     * @param selectCriteria
     * @return
     */
    @PostMapping("/partitionList")
    public CommonResult<PageDTO> partitionList(MerchantDTO merchantDTO,
                                               @RequestBody PartitionPageCriteria selectCriteria) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        List<Integer> ids = merchantService.selectIds(merchantDTO.getId());
        PageDTO dto = new PageDTO();
        if (CollUtil.isEmpty(ids)) {
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询下级商户分区成功", dto);
        }
        selectCriteria.setIds(ids);
        PageHelper.startPage(selectCriteria.getPageNum(), selectCriteria.getPageSize());
        List<PartitionDTO> partitionDTOS = partitionService.selectByPage(selectCriteria);
        PageInfo<PartitionDTO> pageInfo = new PageInfo<>(partitionDTOS);
        dto = BeanConvertUtils.convert(pageInfo, PageDTO.class);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "查询下级商户分区成功", dto);
    }

    /**
     * 代理统计
     * @param merchantDTO
     * @return
     */
    @PostMapping("/topUpStatistics")
    public CommonResult<StatisticsPageDTO> topUpStatistics(MerchantDTO merchantDTO,@RequestBody StatisticsCriteria statistics) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        statistics.setProxyId(merchantDTO.getId());
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "代理统计查询成功", orderService.topUpStatistics(statistics));
    }

    /**
     * 获取网站设置
     *
     * @return
     */
    @GetMapping("/netConfig")
    public CommonResult<NetConfigDTO> netConfig(MerchantDTO merchantDTO) {
        if (!"PROXY".equals(merchantDTO.getMerchantType())){
            return new CommonResult(8100, "非代理商户，无权访问");
        }
        NetConfigDTO netConfigDTO = netConfigService.getNetConfig();
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "成功", netConfigDTO);
    }


}
